package com.ruoyi.forum.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.forum.domain.CircleLabel;
import com.ruoyi.forum.model.LabelSort;
import com.ruoyi.forum.service.CircleLabelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.ruoyi.forum.constant.CircleConst.CIRCLE_LABEL_MAX_NUM;
import static com.ruoyi.forum.constant.CircleConst.CIRCLE_LABEL_NAME_MAX_LENGTH;

@Tag(name = "论坛板块", description = "论坛板块管理接口")
@RequestMapping(value = "/circle")
@RestController
public class CircleLabelController extends BaseController {

    @Autowired
    private CircleLabelService circleLabelService;

    @Operation(summary = "获取话题标签列表", description = "获取话题标签列表")
    @Parameters({
            @Parameter(name = "page", description = "页码", schema = @Schema(type = "int")),
            @Parameter(name = "pageSize", description = "条数", schema = @Schema(type = "int")),
            @Parameter(name = "name", description = "名称", required = false),
            @Parameter(name = "delFlag", description = "删除标志", required = false)
    })
    @RequestMapping(value = "/label/list", method = RequestMethod.GET)
    public TableDataInfo getLabelList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer page,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer rows,
                                      @RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "delFlag", required = false) Integer delFlag) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleLabel> wrapper = new LambdaQueryWrapper<>();
        if (delFlag != null) {
            wrapper.eq(CircleLabel::getDelFlag, delFlag);
        }
        if (!StringUtils.isEmpty(name)) {
            wrapper.like(CircleLabel::getName, name);
        }

// 设置排序和分页
        Page<CircleLabel> pageInfo = new Page<>(page, rows);
        pageInfo.addOrder(new OrderItem("sort_num", false)); // ASC排序
// 执行分页查询
        IPage<CircleLabel> page1 = circleLabelService.page(pageInfo, wrapper);

        TableDataInfo data = getDataTable(page1.getRecords());
        return data;
    }

    @Log(title = "新增和修改话题列表", businessType = BusinessType.INSERT)
    @Operation(summary = "新增和修改话题列表", description = "新增和修改话题列表")
    @Parameters({
            @Parameter(name = "id", description = "标题id"),
            @Parameter(name = "name", description = "标题名称"),
            @Parameter(name = "sort", description = "排序"),
    })
    @RequestMapping(value = "/label/save", method = RequestMethod.POST)
    public AjaxResult labelSave(@RequestParam(value = "id", required = false) String id,
                                @RequestParam(value = "name") String name,
                                @RequestParam(value = "sort") Integer sort) {
        if (name.trim().length() > CIRCLE_LABEL_NAME_MAX_LENGTH) {
            return AjaxResult.error("板块分区名称超出最大长度限制，请修改后提交");
        }

        CircleLabel circleLabel;
        if (StringUtils.isEmpty(id)) {
            if (circleLabelService.countBySid() >= CIRCLE_LABEL_MAX_NUM) {
                return AjaxResult.error("板块分区数量超出最大限制，不能新增！");
            }
            LambdaQueryWrapper<CircleLabel> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(CircleLabel::getSortNum);
            // 设置分页
            Page<CircleLabel> pageInfo = new Page<>(1, 1);
            // 执行分页查询
            List<CircleLabel> labelList = circleLabelService.page(pageInfo, wrapper).getRecords();
            circleLabel = new CircleLabel();
            circleLabel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            if (labelList != null && labelList.size() > 0) {
                sort = labelList.get(0).getSortNum() + 1;
            }
            circleLabel.setSortNum(sort);
            circleLabel.setDelFlag(0);
            circleLabel.setCreateTime(new Date());
            circleLabel.setName(name);
            String userName = SecurityUtils.getUsername();
            circleLabel.setCreateBy(userName);
            circleLabel.setCreateTime(new Date());
            circleLabelService.save(circleLabel);
        } else {
            circleLabel = circleLabelService.selectById(id);
            circleLabel.setName(name);
            circleLabel.setUpdateTime(new Date());
            String userName = SecurityUtils.getUsername();
            circleLabel.setUpdateBy(userName);
            circleLabelService.update(circleLabel);
        }
        return AjaxResult.success();
    }


    @Operation(summary = "话题标签详情", description = "删除话题标签")
    @Parameter(name = "id", description = "话题标签ID", required = true)
    @GetMapping(value = "/label/{id}")
    public AjaxResult labelInfo(@PathVariable("id") String id) {
        CircleLabel label = circleLabelService.selectById(id);
        return AjaxResult.success(label);
    }

    @Log(title = "删除话题标签", businessType = BusinessType.DELETE)
    @Operation(summary = "删除话题标签", description = "删除话题标签")
    @Parameter(name = "id", description = "话题标签ID", required = true)
    @RequestMapping(value = "/label/delete", method = RequestMethod.POST)
    public AjaxResult deleteLabel(@RequestParam(value = "id") String id) {
        CircleLabel label = circleLabelService.selectById(id);
        if (label == null) {
            return AjaxResult.error("对象信息不存在");
        }
        label.setDelFlag(1);
        label.setUpdateTime(new Date());
        circleLabelService.update(label);
        return AjaxResult.success();
    }

    @Log(title = "话题标签排序", businessType = BusinessType.UPDATE)
    @Operation(summary = "话题标签排序", description = "话题标签排序")
    @RequestMapping(value = "/label/sort", method = RequestMethod.POST)
    public AjaxResult sortLabels(@Parameter(hidden = true) @RequestBody List<LabelSort> labelSorts) {
        if (labelSorts == null) {
            return AjaxResult.error("对象信息不存在");
        }
        circleLabelService.saveList(labelSorts);
        return AjaxResult.success();
    }
}